package com.qm.console.utils;

import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;

/**
 * //                       _oo0oo_
 * //                      o8888888o
 * //                      88" . "88
 * //                      (| -_- |)
 * //                      0\  =  /0
 * //                    ___/`---'\___
 * //                  .' \\|     |// '.
 * //                 / \\|||  :  |||// \
 * //                / _||||| -:- |||||- \
 * //               |   | \\\  -  /// |   |
 * //               | \_|  ''\---/''  |_/ |
 * //               \  .-\__  '-'  ___/-. /
 * //             ___'. .'  /--.--\  `. .'___
 * //          ."" '<  `.___\_<|>_/___.' >' "".
 * //         | | :  `- \`.;`\ _ /`;.`/ - ` : | |
 * //         \  \ `_.   \_ __\ /__ _/   .-` /  /
 * //     =====`-.____`.___ \_____/___.-`___.-'=====
 * //                       `=---='
 * //
 * //
 * //     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 * //
 * //               佛祖保佑         永无BUG
 * <p>
 * com.qm.console.utils
 * Created on 2021/9/9.
 */
public class VideoUtils {
   /**
    * 获取指定视频的帧并保存为图片至指定目录
    * @param file  源视频文件
    * @param framefile  截取帧的图片存放路径
    * @throws Exception
    */
   public static void fetchPic(File file, String framefile) throws Exception{
      FFmpegFrameGrabber ff = new FFmpegFrameGrabber(file);
      ff.start();
      int lenght = ff.getLengthInFrames();

      File targetFile = new File(framefile);
      Frame frame = ff.grabFrame();
      if (frame == null) {
         System.out.println("failed to grep frame.");
         ff.stop();
         return;
      }
      String imgSuffix = "jpg";

      Java2DFrameConverter converter =new Java2DFrameConverter();
      BufferedImage srcBi =converter.getBufferedImage(frame);
      try {
         ImageIO.write(srcBi, imgSuffix, targetFile);
      }catch (Exception e) {
         e.printStackTrace();
      }
      ff.stop();
   }

   /**
    * 获取视频时长，单位为秒
    * @param file
    * @return 时长（s）
    */
   public static Long getVideoTime(File file){
      Long times = 0L;
      try {
         FFmpegFrameGrabber ff = new FFmpegFrameGrabber(file);
         ff.start();
         times = ff.getLengthInTime()/(1000*1000);
         ff.stop();
      } catch (Exception e) {
         e.printStackTrace();
      }
      return times;
   }

   public static void main(String[] args) {
      File videoFile = new File("/Users/danliu/upload/1631174543187.1631157030879171.mp4");
      try {
         fetchPic(videoFile, new File(videoFile.getParent(), "keyFrame.jpg").getAbsolutePath());
      } catch (Exception e) {
      }
   }
}
